package com.manor.main.fragment.square;

import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.manor.common.CommonAppConfig;
import com.manor.common.bean.UserBean;
import com.manor.common.event.LocationEvent;
import com.manor.common.http.HttpCallback;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.StringUtil;
import com.manor.im.activity.HChatRoomActivity;
import com.manor.main.R;
import com.manor.main.adapter.MainBottomSameCityAdapter;
import com.manor.main.bean.BottomSameCityBean;
import com.manor.main.event.SelectMainBottomView;
import com.manor.main.fragment.community.CommunityBaseFragment;
import com.manor.main.http.MainHttpUtil;
import com.tencent.imsdk.v2.V2TIMConversation;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 首页-认证
 */
@Route(path = RouteUtil.MAIN_MSG_FOLLOW)
public class SquareAuthFragment extends CommunityBaseFragment {

    private RecyclerView mRecycleView;
    private MainBottomSameCityAdapter followAdapter;
    private List<BottomSameCityBean> followBeanList = new ArrayList<>();
    private int pageNum = 1;
    private String auth = "1";
    //    private List<List<BottomSameCityBean>> followCityListList = new ArrayList<>();
    private UserBean mUserBean;
    private boolean hasMore = true;


    private String sex = "1";
    private String psex = "1";
    private String isVideo = "";
    private String isVoice = "";
    private String lastId = "";
    private SmartRefreshLayout refreshLayout;
    public static SquareAuthFragment newInstance() {
        SquareAuthFragment fragment = new SquareAuthFragment();
        return fragment;
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        KLog.e("tag","isVisibleToUser"+isVisibleToUser);
        if(isVisibleToUser){

        }

    }

    @Override
    public void onStop() {
        super.onStop();
        KLog.e("tag","onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        KLog.e("tag","onDestroy");
    }

    @Override
    protected void initData() {
        getUserInfo();
        loadDate();

        followAdapter = new MainBottomSameCityAdapter(R.layout.rv_mainsamecity_item, followBeanList);

        followAdapter.setEmptyView(R.layout.view_no_data_common);
//        followAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mRecycleView.setAdapter(followAdapter);


        followAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position>=followBeanList.size())
                    return;
                String toId = followBeanList.get(position).getId();
                if (StringUtil.isNotEmpty(toId)) {
                    if (ClickUtil.canClick()) {
                        EventBus.getDefault().post(new MainOnclickEvent(toId));
//                        if (null != mListener) {
//                            mListener.onItemClick(toId);
//                        }
                    }
                }
                return;
            }
        });

        EventBus.getDefault().register(this);


        followAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //获取这个用户的信息，然后跳转去聊天
                if (!"".equals(followBeanList.get(position).getId())) {
                    if (ClickUtil.canClick()) {

                        BottomSameCityBean it = followBeanList.get(position);
                        mUserBean = new UserBean();
                        mUserBean.setUserNiceName(it.getUser_nickname());
                        mUserBean.setFollows(1);
                        mUserBean.setId(it.getId());
                        String avatar = "";
                        if (!"".equals(it.getAvatar())) {
                            avatar = it.getAvatar();
                            mUserBean.setAvatar(it.getAvatar());
                        }
//                        if (!"".equals(it.getThumb())) {
//                            avatar = it.getThumb();
//                            mUserBean.setAvatarThumb(it.getThumb());
//                        }
                        //跳转去聊天
                        //ChatRoomActivity.forward(getContext(), mUserBean, mUserBean.isFollowing(),
                        //  mUserBean.isBlacking(), true, false);

                        if (getActivity()!=null)
                            HChatRoomActivity.Companion.forward(getActivity(),it.getId(),it.getUser_nickname(),avatar, V2TIMConversation.V2TIM_C2C);

                    }
                }
            }
        });


    }

    private void getUserInfo() {
        UserBean userBean = CommonAppConfig.getInstance().getUserBean();

        if(null==userBean){
            return;
        }
        sex = userBean.getSex();
        if (null!=sex&&sex.equals("1")) {
            psex = "2";
        } else {
            psex = "1";
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }



    private void loadDate() {
        if (StringUtil.isListNotEmpty(followBeanList)){
            lastId = followBeanList.get(followBeanList.size()-1).getId();
        }else {
            lastId = "";
        }
        setDate(pageNum, psex, auth, isVideo, isVoice,lastId);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLocalSuc(LocationEvent event) {
        Logger.e("onLocalSuc event---");
        if (event != null) {
            pageNum = 1;
            loadDate();
        }

    }


    /**
     * 显示页面后 刷新当前的认证数据
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateBottomView(SelectMainBottomView event) {
        if (event != null) {
            if (event.getSelectView() == 1) {
                Logger.i("调用底部刷新数据----updateBottomView" + event.getSelectView());
                pageNum = 0;
                lastId = "";
                hasMore = true;
                //TODO 是否还要根据上次选择的性别来刷新当前的数据
                setDate(pageNum, psex, auth, isVideo, isVoice, lastId);
            }
        }
    }


    @Override
    public int onSetLayoutId() {
        return R.layout.fragment_square_follow;
    }

    @Override
    public void initView() {
        mRecycleView = mContentView.findViewById(R.id.recycler_view);
        refreshLayout = mContentView.findViewById(R.id.refreshLayout);
//        WrapContentLinearLayoutManager wrapContentLinearLayoutManager = new WrapContentLinearLayoutManager(getContext());
//        mRecycleView.setLayoutManager(wrapContentLinearLayoutManager);
        mRecycleView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        followAdapter = new MainBottomSameCityAdapter(R.layout.rv_mainsamecity_item, null);

//        followAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mRecycleView.setAdapter(followAdapter);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum ++;
                loadDate();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout)
            {
                pageNum = 1;
                loadDate();

            }
        });

    }




    /**
     * @param p    页码
     * @param auth 是否认证  0未认证/1已认证   setDate(pageNum, psex, auth, isVideo, isVoice);
     */
    private void setDate(int p, String psex, String auth, String isVideo, String isVoice,String lastId) {
        MainHttpUtil.getNear(p, psex, auth, isVideo, isVoice,lastId, new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String info) {
                if (code == 0) {
                    if (StringUtil.isNotEmpty(info)) {
                        setFollowDate(code, msg, info);

                    } else {
                        hasMore = false;

                    }
                } else {

                }

            }

            @Override
            public void onError() {
                super.onError();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                if (followAdapter != null) {
                    pageNum--;

                }
            }
        });
    }


    private void setFollowDate(int code, String msg, String info) {
        if (code == 0 && StringUtil.isNotEmpty(info)) {
            List<BottomSameCityBean> mList = JSON.parseArray(info, BottomSameCityBean.class);

            if (pageNum == 1) {
                followBeanList.clear();
                followAdapter.setNewInstance(mList);

                refreshLayout.finishRefresh();
            }else {
                followAdapter.addData(mList);
                refreshLayout.finishLoadMore();
            }
            followBeanList.addAll(mList);
//            for (int i = 0; i < followBeanList.size(); i++) {
//                followCityListList.add(followBeanList);
//            }
            followAdapter.notifyDataSetChanged();
        }

    }


    @Override
    public void bindEvent() {

    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void initImmersionBar() {

    }

    @Override
    public boolean immersionBarEnabled() {
        return false;
    }


    /**
     * 点击筛选后的条件查询
     *
     * @param filterEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFilterEvent(FilterEvent filterEvent) {
        if (filterEvent != null) {
            psex = filterEvent.getSex();
            byte chatType = filterEvent.getChatType();
            int selectView = filterEvent.getSelectView();
            Logger.i("onFilterEvent接收到的数据是：" + sex + "---" + chatType);


            if (chatType == 0) {
                isVideo = 1 + "";
                isVoice = 1 + "";
            } else if (chatType == 1) {
                isVideo = 1 + "";
                isVoice = 0 + "";
            } else if (chatType == 2) {
                isVideo = 0 + "";
                isVoice = 1 + "";
            }

            if (selectView == 1) {
                Logger.i("调用底部刷新数据" + selectView);
                if (followBeanList.size() > 0) {
                    followBeanList.clear();
                }
                pageNum = 1;
                hasMore = true;
                lastId = "";
                setDate(pageNum, psex, auth, isVideo, isVoice, lastId);
            }

        }
    }


}
